#include "../include/PageLib.h"
#include "../include/Configuration.h"
#include "../include/DirScanner.h"
#include "../include/FileProcessor.h"

#include <fstream>

using std::ofstream;
using std::make_pair;

PageLib::PageLib(Configuration *pconf, DirScanner &dirScanner, FileProcessor &fileProcessor)
: _dirScanner(dirScanner)
, _fileProcessor(fileProcessor)
{
    map<string, string> tmp = pconf->getConfigMap();
    _dirScanner.traverse(tmp["webPage"]);
}

PageLib::~PageLib() {

}

void PageLib::create() {
    vector<string> tmpPath = _dirScanner.files();
    cout << tmpPath.size() << endl;
    for (auto it = tmpPath.begin(); it != tmpPath.end(); ++it) {
        _fileProcessor.process(*it, _files);
        _fileProcessor.clearVec();
    }
}

void PageLib::store() {
    ofstream ofs1("../data/ripepage.dat", std::ios::out|std::ios::app);
    if (!ofs1.good()) {
        cout <<"ofstrem open file error" << endl;
        return;
    }

    int count = 1;
    int beginOffset = 0;
    for (auto it = _files.begin(); it != _files.end(); ++it) {
        ofs1 << *it;
        _offsetLib[count++] = make_pair(beginOffset, (*it).size());
        beginOffset += (*it).size();
    }    
    ofs1.close();

    ofstream ofs2("../data/offset.dat", std::ios::out|std::ios::app);
    if (!ofs2.good()) {
        cout <<"ofstrem open file error" << endl;
        return;
    }
    for (auto &elem: _offsetLib) {
        ostringstream oss;
        oss << elem.first << " " << elem.second.first << " " << elem.second.second << endl;
        ofs2 << oss.str();
    }
    ofs2.close();
}        
         
vector<string> &PageLib::getFiles() {
    return _files;
}
